package net.lesscoding.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.lesscoding.common.Result;
import net.lesscoding.common.ResultFactory;
import net.lesscoding.entity.OutPathConfig;
import net.lesscoding.mapper.OutPathConfigMapper;
import net.lesscoding.service.OutPathConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author eleven
 * @date  2022-08-05 15:30:41
 * @description out_path_config 输出路径配置表实体类
 * Generated By: lesscoding.net basic service
 * Link to: <a href="https://lesscoding.net">https://lesscoding.net</a>
 * mail to:2496290990@qq.com zjh292411@gmail.com admin@lesscoding.net
 */
@Service
@Slf4j
public class OutPathConfigServiceImpl extends ServiceImpl<OutPathConfigMapper, OutPathConfig> implements OutPathConfigService {

    @Autowired
    private OutPathConfigMapper outPathConfigMapper;

    /**
     * 根据条件分页查询表格结果
     * @return Result
     */
    @Override
    public Result getPageByLike(OutPathConfig outPathConfig){
        PageHelper.startPage(outPathConfig.getCurrentPage(),outPathConfig.getPageSize());
        List<OutPathConfig> pageByLike = outPathConfigMapper.getPageByLike(outPathConfig);
        PageInfo<OutPathConfig> info = new PageInfo<>(pageByLike);
        info.setTotal(pageByLike.size());
        return ResultFactory.returnPage(info);
    }

    /**
     * 下载导入模板
     * @param response
     */
    @Override
    public void downloadTemplate(HttpServletResponse response){
        try(OutputStream os = response.getOutputStream()) {
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("text.xlsx", "UTF-8"));
            response.setHeader("Connection", "close");
            response.setHeader("Content-Type", "application/octet-stream");
            EasyExcel.write(os,OutPathConfig.class)
                    .sheet("导出")
                    .doWrite(new ArrayList<>());
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 从excel批量导入数据
     * @return
     */
    @Override
    public Result import4Excel(MultipartFile file){
        try (InputStream is = file.getInputStream()){
            EasyExcel.read(is, OutPathConfig.class, new ReadListener() {

                /**
                 * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
                 */
                private static final int BATCH_COUNT = 512;
                /**
                 * 缓存的数据
                 */
                private List<OutPathConfig> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

                @Override
                public void invoke(Object o, AnalysisContext analysisContext) {
                    OutPathConfig outPathConfig = (OutPathConfig) o;
                    cachedDataList.add(outPathConfig);
                    if(cachedDataList.size() >= BATCH_COUNT) {
                        ExecutorService executorService = new ThreadPoolExecutor(1, 8,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>(8));
                        executorService.execute(() -> outPathConfigMapper.insertBatch(cachedDataList));
                        cachedDataList.clear();
                    }
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                }
            }).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultFactory.success("导入成功");
    }


    /**
    * 导出为excel
    * @param response
    */
    @Override
    public void export2Excel(OutPathConfig outPathConfig, HttpServletResponse response){
        List<OutPathConfig> list = outPathConfigMapper.getPageByLike(outPathConfig);
        try {
            EasyExcel.write(response.getOutputStream(),OutPathConfig.class)
                    .sheet("导出")
                    .doWrite(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据id查询详情
     * @param id 要查询的详情
     * @return
     */
    @Override
    public Result getOutPathConfigById(Integer id){
        return null;
    }

    /**
     * 根据id删除
     * @return
     */
    @Override
    public Result delOutPathConfigById(Integer id){
        return null;
    }

    /**
     * 保存或编辑
     * @return
     */
    @Override
    public Result saveOrUpdateOutPathConfig(OutPathConfig outPathConfig){
        int effect = outPathConfig.getId() != null ?
                outPathConfigMapper.insert(outPathConfig) :
                outPathConfigMapper.updateById(outPathConfig);
        return ResultFactory.buildByResult(effect);
    }
}